<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入订单总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:productOrders:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:productOrders:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:productOrders:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:productOrders:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productOrdersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="orderId"/>
      <el-table-column label="用户id" align="center" prop="userId"/>
      <el-table-column label="用户名称" align="center" prop="userName"/>
      <el-table-column label="订单号" align="center" prop="orderNumber"/>
      <el-table-column label="订单总金额" align="center" prop="totalAmount"/>
      <el-table-column label="支付状态" align="center" prop="paymentStatus"/>
      <el-table-column label="物流状态" align="center" prop="shippingStatus"/>
      <el-form-item label="订单类型" prop="ordersType">
        <el-select v-model="form.ordersType" placeholder="请选择订单类型">
          <el-option
            v-for="dict in dict.type.orders_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:productOrders:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:productOrders:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-divider content-position="center">发货信息</el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="收货信息">
              <el-input v-model="sysUseConsigneeInfoText" disabled type="textarea" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="收货人">
              <el-input v-model="sysUseConsigneeInfo.consigneeName" disabled maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="收货地址">
              <el-input v-model="sysUseConsigneeInfo.consigneeAddress" disabled maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">订单信息</el-divider>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form.orderNumber" disabled placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" disabled placeholder="请输入订单总金额"/>
        </el-form-item>
        <el-form-item label="订单类型" prop="ordersType">
          <el-select v-model="form.ordersType" placeholder="请选择订单类型" disabled filterable clearable>
            <el-option
              v-for="dict in dict.type.orders_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-divider content-position="center">订单明细信息</el-divider>
        <template v-for="(item, index) in productOrderDetailsList">
          <el-row>
            <el-col :span="6">
              <el-form-item>
                <image-preview width="150px" height="150px" :src="item.productUrl"/>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="商品名称">
                    <span>{{ item.productName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="商品数量">
                    <span>{{ item.quantity }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="商品积分">
                    <span>{{ item.pricePerUnit }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品小计">
                    <span>{{ item.subtotal }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
        <el-divider content-position="center">物流信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="物流单号" prop="shippingNumber">
              <el-input v-model="form.shippingNumber" placeholder="请输入物流单号"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="请选择物流公司" label-width="150px" prop="shippingCompany">
              <el-select v-model="form.shippingCompany" placeholder="请选择物流公司" filterable clearable
                         :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.shipping_company"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :disabled="dict.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物流详情">
              <el-input v-model="shippingInfoText" disabled type="textarea" maxlength="30" rows="10"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProductOrders,
  getProductOrders,
  delProductOrders,
  addProductOrders,
  updateProductOrders
} from "@/api/system/productOrders";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "ProductOrders",
  components: {Treeselect},
  dicts: ['orders_type', 'shipping_company'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedProductOrderDetails: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品订单表格数据
      productOrdersList: [],
      // 订单明细表格数据
      productOrderDetailsList: [],
      productInfo: {},
      sysUseConsigneeInfoText: '',
      shippingInfoText: '',
      sysUseConsigneeInfo: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        orderNumber: null,
        totalAmount: null,
        addressId: null,
        paymentStatus: null,
        shippingStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品订单列表 */
    getList() {
      this.loading = true;
      listProductOrders(this.queryParams).then(response => {
        this.productOrdersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        userId: null,
        orderNumber: null,
        totalAmount: null,
        addressId: null,
        paymentStatus: null,
        shippingStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.productOrderDetailsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getProductOrders(orderId).then(response => {
        this.form = response.data;
        this.productOrderDetailsList = response.data.productOrderDetailsList;
        this.sysUseConsigneeInfoText = response.data.sysUseConsigneeInfo.consigneeName + "  " + response.data.sysUseConsigneeInfo.consigneePhone + "  " + response.data.sysUseConsigneeInfo.consigneeAddress;
        this.sysUseConsigneeInfo = response.data.sysUseConsigneeInfo;
        let shipping = '';
        response.data.shippingRecordList.forEach(item => {
          shipping = shipping + item.context + "\n" + item.time + "\n";
        })
        this.shippingInfoText = shipping;
        this.open = true;
        this.title = "修改商品订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.productOrderDetailsList = this.productOrderDetailsList;
          if (this.form.orderId != null) {
            updateProductOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除商品订单编号为"' + orderIds + '"的数据项？').then(function () {
        return delProductOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 订单明细序号 */
    rowProductOrderDetailsIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 订单明细添加按钮操作 */
    handleAddProductOrderDetails() {
      let obj = {};
      obj.productId = "";
      obj.quantity = "";
      obj.pricePerUnit = "";
      obj.subtotal = "";
      obj.productUrl = "";
      obj.remark = "";
      this.productOrderDetailsList.push(obj);
    },
    /** 订单明细删除按钮操作 */
    handleDeleteProductOrderDetails() {
      if (this.checkedProductOrderDetails.length == 0) {
        this.$modal.msgError("请先选择要删除的订单明细数据");
      } else {
        const productOrderDetailsList = this.productOrderDetailsList;
        const checkedProductOrderDetails = this.checkedProductOrderDetails;
        this.productOrderDetailsList = productOrderDetailsList.filter(function (item) {
          return checkedProductOrderDetails.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleProductOrderDetailsSelectionChange(selection) {
      this.checkedProductOrderDetails = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/productOrders/export', {
        ...this.queryParams
      }, `productOrders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
